package com.ruoyi.business.component.mqconsumer;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.service.ILoanService;
import com.ruoyi.common.config.RocketMqTopics;
import com.ruoyi.common.utils.FeishuUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.ruoyi.business.service.ILoanApplyService.LOAN_APPLY_TOPIC;
import static com.ruoyi.business.service.ILoanApplyService.LOAN_RESULT_TOPIC;

/**
 * 放款结果消费
 *
 * @author cyh
 * @date 2022/5/11 11:45 上午
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "${rocketmq.consumers.loanResultConsumer}",  topic = "${rocketmq.consumer-topics.loanResultTopic}",
        messageModel = MessageModel.CLUSTERING,
        consumeMode = ConsumeMode.ORDERLY,
        consumeTimeout = 300L)
public class LoanResultConsume implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {

    public static final String SUCCESS = "success";
    public static final String FAILED = "failed";

    @Autowired
    private ILoanService loanService;

    @Override
    public void onMessage(MessageExt messageExt) {
        String messageId = messageExt.getMsgId();
        log.info("放款结果 MQ 消费开始 >>> messageId：{}", messageId);

        JSONObject loanResultJson = JSONObject.parseObject(new String(messageExt.getBody()));
        log.info("待消费的放款结果消息，messageId = {}, messageBody = {}", messageId, loanResultJson);

        String loanSerialNo = loanResultJson.getString("loanSerialNo");
        try {
            String result = loanResultJson.getString("result");
            loanService.dealLoanResult(loanSerialNo, result);
        } catch (Exception e) {
            log.error("放款结果消费 error，messageId = {}, messageBody = {}", messageId, loanResultJson, e);

            // 发送监控
            FeishuUtils.sendFeishuToMonit(loanSerialNo, "MQ 消费者-放款", loanSerialNo, loanResultJson.toString(), e);
            throw new RuntimeException();
        }

        log.info("放款结果 MQ 消费结束 >>> messageId = {}，messageBody = {}", messageId, loanResultJson);
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer consumer) {
        // 设置最大重试次数
        consumer.setMaxReconsumeTimes(RocketMqTopics.getMaxReconsumeTimes());
        // 如下，设置其它consumer相关属性
        // consumer.setPullBatchSize(16);
    }
}
